/*
 * @Description: 操作日志列表
 * @Author: Rfan
 * @Date: 2022-11-18 18:48:01
 * @LastEditTime: 2022-11-19 15:27:34
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, message, Modal, Space, Table } from 'antd';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { formatDate } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useLogContext } from '@/view/logMgt/Log/contexts/LogContext';
import { deleteOperateLog, fetchOperateLogListByPage } from '@/api/log/operate';
import { delItemByIdArray } from '@/utils/list';
import OperateDetailDialog from '@/view/logMgt/Log/components/dialogs/OperateDetail';
import type { IPageQuery } from '@/interfaces/global';

dayjs.extend(duration);

const { Column } = Table;

const OperateList = () => {
  const { logType, selectItems, setSelectKey } = useLogContext();
  const formatMessage = useFormatMessage();
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  const [selectInfo, setSelectInfo] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);

  useEffect(() => {
    if (listQuery && logType === 'operate') {
      setLoading(true);
      fetchOperateLogListByPage(listQuery)
        .then((res) => {
          const { data } = res;
          console.log('operate list', data);
          setTotal(data.pageCount);
          setList(data.results);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const delLogItem = (id: number) => {
    Modal.confirm({
      title: '删除',
      content: '确定删除选中的日志？',
      onOk() {
        deleteOperateLog(id).then((res) => {
          message.success('删除成功');
          const data = res.data.map((item: string) => parseInt(item, 10));
          setList((state) => delItemByIdArray(data, state));
        });
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };

  const showDetail = (info: any) => {
    setSelectInfo(info);
    setDetailVisible(true);
  };

  return (
    <>
      <Table
        dataSource={list}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" />
        <Column title="根路径" dataIndex="basePath" key="basePath" />
        <Column title="ip" dataIndex="ip" key="ip" />
        <Column title="URI" dataIndex="uri" key="uri" />
        <Column title="URL" dataIndex="url" key="url" />
        <Column title="请求类型" dataIndex="method" key="method" />
        <Column title="操作者" dataIndex="userName" key="userName" />
        <Column
          title="操作时间"
          dataIndex="operateTime"
          key="operateTime"
          render={(text) => formatDate(text)}
        />
        <Column
          title="消耗时间"
          dataIndex="spendTime"
          key="spendTime"
          render={(text) => dayjs.duration(text).asMilliseconds() + 'ms'}
        />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                size="small"
                onClick={() => {
                  showDetail(record);
                }}
              >
                详情
              </Button>
              <Button
                type="link"
                size="small"
                onClick={() => {
                  delLogItem(record.id);
                }}
              >
                删除
              </Button>
            </Space>
          )}
        />
      </Table>

      {useMemo(() => {
        return (
          selectInfo && (
            <OperateDetailDialog
              data={selectInfo}
              visible={detailVisible}
              onClose={() => {
                setDetailVisible(false);
              }}
            />
          )
        );
      }, [detailVisible])}
    </>
  );
};

export default OperateList;
